import json
import os

archive_path = 'resources/assets/kuayue/'
blockstates_path = archive_path + 'blockstates/'
model_path = archive_path + 'models/'
texture_path = archive_path + 'textures/'
lang_path = archive_path + 'lang/'
block_model_path = model_path + 'block/'
item_model_path = model_path + 'item/'
block_texture_path = texture_path + 'block/'
item_texture_path = texture_path + 'item/'
archive_name = 'kuayue'
data_path = 'resources/data/'
kuayue_data = data_path + 'kuayue/'
minecraft_data = data_path + 'minecraft/'
forge_data = data_path + 'forge/'
create_data = data_path + 'create/'
loot_table_path = kuayue_data + 'loot_tables/'
recipes_path = kuayue_data + 'recipes'
tags_block = 'tags/blocks/'
mineable_tags = tags_block + 'mineable/'

blockstates_list = []
lang_list = []
tags_list = []
loot_tables_list = []
advancements_list = []
recipes_list = []
stack_trace = True


class blockstate_file:
    path = ""
    content = None
    name = ""
    dirty = False
    major_key = 'variants'
    type = '.json'

    def __init__(self, path: str, name: str):
        self.path = path
        self.name = name

    def read(self):
        with open(self.__get_full_path__(), 'r') as f:
            self.content = json.loads(f.read())

    def write(self):
        if self.content is None:
            return
        if not self.dirty:
            return
        f = open(self.__get_full_path__(), 'w')
        f.writelines(json.dumps(self.content, indent=1))
        f.close()
        self.dirty = False

    def remove_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            os.remove(self.__get_full_path__())

    def make_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            return
        if not os.path.exists(self.__get_path__()):
            os.makedirs(self.__get_path__())
        self.write()

    def __get_full_path__(self):
        return blockstates_path + ((self.path + '/') if self.path != '' else '') + self.name + self.type

    def __get_path__(self):
        return blockstates_path + self.path

    def get_properties(self):
        if self.content is None:
            self.read()
        if self.content is None:
            return []
        vars = dict(self.content)
        vars = vars.get(self.major_key)
        if not isinstance(vars, dict):
            return []
        vars = dict(vars)
        for i in vars.keys():
            vals = str(i).split(',')
            counter = 0
            for i in vals:
                vals[counter] = i.split('=')[0]
                counter += 1
            return vals
        return []

    def rename(self, new_name: str):
        if self.name != new_name:
            self.remove_file()
            old_name = self.name
            self.name = new_name
            self.dirty = True
            self.make_file()
            if stack_trace:
                print('-> renamed blockstate', old_name, 'as', self.name)
        pass

    def move(self, new_path: str):
        if self.path != new_path:
            self.remove_file()
            old_path = self.path
            self.path = new_path
            self.dirty = True
            self.make_file()
            if stack_trace:
                print('-> move blockstate from', old_path, 'to', self.path)
        pass

    def rename_and_move(self, new_path: str, new_name: str):
        if self.content is None:
            return
        if self.name != new_name or self.path != new_path:
            self.remove_file()
            old_path = self.path
            old_name = self.name
            self.path = new_path
            self.name = new_name
            self.dirty = True
            self.make_file()
            if stack_trace:
                print('-> changed blockstate from', ((old_path + '/') if old_path != '' else '') + old_name, 'to',
                      ((self.path + '/') if self.path != '' else '') + self.name)

    def on_move_model(self, old_path: str, new_path: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return
        varx = self.content.get(self.major_key)
        if not isinstance(varx, dict):
            return
        for i in varx.values():
            if not isinstance(i, dict):
                continue
            if not i.__contains__('model'):
                continue
            if not i['model'] == archive_name + ':' + old_path:
                continue
            i['model'] = archive_name + ':' + new_path
        self.write()

    def print(self):
        print('path:', self.path, 'name:', self.name)
        print(self.content)
        pass


class lang_file:
    content = None
    name = ''
    type = '.json'
    dirty = False

    def __init__(self, name: str):
        self.name = name

    def read(self):
        encoding = 'gbk' if self.name == 'zh_cn' else 'utf-8'
        with open(archive_path + 'lang/' + self.name + self.type, 'r', encoding=encoding) as f:
            self.content = json.loads(f.read())

    def write(self):
        if self.content is None:
            return
        if not self.dirty:
            return
        encoding = 'gbk' if self.name == 'zh_cn' else 'utf-8'
        with open(archive_path + 'lang/' + self.name + self.type, 'wb') as f:
            s = json.dumps(self.content, indent=1, ensure_ascii=False).encode('utf-8')
            f.write(s)
            self.dirty = False

    def on_blockstate_rename(self, old_key: str, new_key: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return
        should_replace = [i for i in self.content.keys() if is_valid_for_rename(i, old_key)]
        for i in should_replace:
            val = self.content.pop(i)
            self.content[i.replace(old_key, new_key)] = val
            self.dirty = True
        if stack_trace and self.dirty:
            print('-> updated lang file', self.name)
        self.write()


def is_valid_for_rename(name: str, key: str):
    if not name.startswith('block.' + archive_name + '.' + key):
        return False
    n = name.replace('block.' + archive_name + '.' + key, '')
    n = n.replace('_', '').replace('tooltip', '').replace('.', '')
    if len(n) == 0:
        return True
    return n.isdigit()


class tag_file:
    content = None
    path = ''
    name = ''
    namespace = 'kuayue'
    type = '.json'
    dirty = False

    def __init__(self, namespace: str, path: str, name: str):
        self.path = path
        self.name = name
        self.namespace = namespace

    def read(self):
        with open(self.__get_full_path__(), 'r') as f:
            self.content = json.loads(f.read())

    def write(self):
        if self.content is None:
            return
        if not self.dirty:
            return
        with open(self.__get_full_path__(), 'w') as f:
            f.write(json.dumps(self.content, indent=1))
            self.dirty = False

    def make_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            return
        if not os.path.exists(self.__get_path__()):
            os.makedirs(self.__get_path__())
        self.write()

    def remove_file(self):
        if self.content is None:
            return
        if not os.path.exists(self.__get_full_path__()):
            return
        os.remove(self.__get_full_path__())

    def __get_full_path__(self):
        return data_path + self.namespace + '/tags/' + (
            (self.path + '/') if self.path != '' else '') + self.name + self.type

    def __get_path__(self):
        return data_path + self.namespace + '/tags/' + self.path

    def on_blockstate_rename(self, old_key: str, new_key: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return

        values = dict(self.content).get('values')
        if not isinstance(values, list):
            return
        v = list(values)
        if v.__contains__(archive_name + ':' + old_key):
            v[v.index(archive_name + ':' + old_key)] = archive_name + ':' + new_key
            self.dirty = True
            self.write()
            if stack_trace:
                print('-> updated tag', self.name)

    def print(self):
        print('namespace:', self.namespace, ', path:', self.path, ', name:', self.name)
        print(json.dumps(self.content, indent=1))


class loot_table_file:
    content = None
    name = ''
    path = ''
    type = '.json'
    loot_type = 'minecraft:block'
    dirty = False

    def __init__(self, path: str, name: str):
        self.path = path
        self.name = name

    def read(self):
        with open(self.__get_full_path__(), 'r') as f:
            self.content = json.loads(f.read())
        if self.content is None:
            return
        self.loot_type = self.content.get('type')

    def write(self):
        if not self.dirty:
            return
        if self.content is None:
            return
        with open(self.__get_full_path__(), 'w') as f:
            f.write(json.dumps(self.content, indent=1))
        self.dirty = False

    def remove_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            os.remove(self.__get_full_path__())

    def make_file(self):
        if self.content is None:
            return
        if not os.path.exists(self.__get_path__()):
            os.makedirs(self.__get_path__())
        self.write()

    def rename(self, new_name: str):
        if new_name == self.name:
            return
        self.remove_file()
        old_name = self.name
        self.name = new_name
        self.dirty = True
        self.make_file()
        if stack_trace:
            print('-> renamed loot file', old_name, 'as', self.name)

    def __get_full_path__(self):
        return kuayue_data + 'loot_tables/' + ((self.path + '/') if self.path != '' else '') + self.name + self.type

    def __get_path__(self):
        return kuayue_data + 'loot_tables/' + self.path

    def on_blockstate_rename(self, old_key: str, new_key: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return
        if self.name == old_key:
            self.rename(new_key)
        pools = list(self.content.get('pools'))
        for pool in pools:
            entries = list(pool.get('entries'))
            for entry in entries:
                if entry['name'] == archive_name + ':' + old_key:
                    entry['name'] = archive_name + ':' + new_key
                    self.dirty = True
        if stack_trace and self.dirty:
            print('-> updated loot file', self.name)
        self.write()

    def print(self):
        print('path:', self.path, ', name:', self.name)
        print(json.dumps(self.content, indent=1))


class advancement_file:
    content = None
    name = ''
    type = '.json'
    dirty = False

    def __init__(self, name: str):
        self.name = name

    def read(self):
        with open(self.__get_full_path__(), 'r') as f:
            self.content = json.loads(f.read())

    def write(self):
        if self.content is None:
            return
        if not self.dirty:
            return
        with open(self.__get_full_path__(), 'w') as f:
            f.write(json.dumps(self.content, indent=1))
        self.dirty = False

    def __get_full_path__(self):
        return kuayue_data + 'advancements/' + self.name + self.type

    def on_blockstate_rename(self, old_key: str, new_key: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return
        display = self.content.get('display')
        if display.__contains__('icon'):
            icon = display.get('icon')
            if icon.__contains__('item'):
                item = icon.get('item')
                if item == archive_name + ':' + old_key:
                    icon['item'] = archive_name + ':' + new_key
                    self.dirty = True

        if display.__contains__('criteria'):
            criteria = display.get('criteria')
            for v in criteria.values():
                if v.__contains__('conditions'):
                    conditions = v.get('conditions')
                    for v1 in conditions.values():
                        if v1.__contains__('items'):
                            items = v1.get('items')
                            for v2 in items.values():
                                if v2.__contains__('items'):
                                    items2 = v2.get('items')
                                    for i in range(len(items2)):
                                        if items2[i] == archive_name + ':' + old_key:
                                            items2[i] = archive_name + ':' + new_key
                                            self.dirty = True
        if stack_trace and self.dirty:
            print('-> updated advancement file', self.name)
        self.write()

    def print(self):
        print('name:', self.name)
        print(json.dumps(self.content, indent=1))


class recipe_file:
    content = None
    name = ''
    path = ''
    type = '.json'
    dirty = False

    def __init__(self, path: str, name: str):
        self.name = name
        self.path = path

    def read(self):
        with open(self.__get_full_path__(), 'r') as f:
            self.content = json.loads(f.read())

    def write(self):
        if self.content is None:
            return
        if not self.dirty:
            return
        with open(self.__get_full_path__(), 'w') as f:
            f.write(json.dumps(self.content, indent=1))
        self.dirty = False

    def make_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            return
        if not os.path.exists(self.__get_path__()):
            os.makedirs(self.__get_path__())
        self.write()

    def remove_file(self):
        if self.content is None:
            return
        if os.path.exists(self.__get_full_path__()):
            os.remove(self.__get_full_path__())

    def __get_full_path__(self):
        return kuayue_data + 'recipes/' + ((self.path + '/') if self.path != '' else '') + self.name + self.type

    def __get_path__(self):
        return kuayue_data + 'recipes/' + self.path

    def on_blockstate_rename(self, old_key: str, new_key: str):
        if self.content is None:
            self.read()
        if self.content is None:
            return
        if self.name.__contains__(old_key):
            self.remove_file()
            old_name = self.name
            self.name.replace(old_key, new_key)
            self.dirty = True
            self.make_file()
            if stack_trace:
                print('-> renamed recipe file', old_name, 'as', self.name)
        if self.content.__contains__('sequence'):
            for i in self.content.get('sequence'):
                self.__rename_keys__(i, old_key, new_key)
        self.__rename_keys__(self.content, old_key, new_key)
        if stack_trace and self.dirty:
            print('-> updated recipe file', self.name)
        self.write()

    def __rename_keys__(self, content, old_key: str, new_key: str):
        if content.__contains__('transitionalItem'):
            transitional_item = content.get('transitionalItem')
            if transitional_item.__contains__('item'):
                item = transitional_item.get('item')
                if item == archive_name + ':' + old_key:
                    transitional_item['item'] = archive_name + ':' + new_key
                    self.dirty = True
        if content.__contains__('key'):
            keys = content.get('key')
            if isinstance(keys, dict):
                for v in keys.values():
                    if v.__contains__('item'):
                        item = v.get('item')
                        if item == archive_name + ':' + old_key:
                            v['item'] = archive_name + ':' + new_key
                            self.dirty = True
        elif content.__contains__('ingredient'):
            ingredient = content.get("ingredient")
            if ingredient.__contains__('item'):
                if ingredient.get('item') == archive_name + ':' + old_key:
                    ingredient['item'] = archive_name + ':' + new_key
                    self.dirty = True
        elif content.__contains__('ingredients'):
            ingredients = content.get('ingredients')
            for v in ingredients:
                if v.__contains__('item'):
                    if v['item'] == archive_name + ':' + old_key:
                        v['item'] = archive_name + ':' + new_key
                        self.dirty = True

        if content.__contains__('result'):
            result = content.get('result')
            if result.__contains__('item'):
                if result['item'] == archive_name + ':' + old_key:
                    result['item'] = archive_name + ':' + new_key
                    self.dirty = True
        elif content.__contains__('results'):
            for i in content.get('results'):
                if i.__contains__('item'):
                    if i['item'] == archive_name + ':' + old_key:
                        i['item'] = archive_name + ':' + new_key
                        self.dirty = True

    def print(self):
        print('path:', self.path, 'name:', self.name)
        print(json.dumps(self.content, indent=1))


def scan_blockstates():
    result = []
    for folder_name, sub_folders, filenames in os.walk(blockstates_path):
        for i in filenames:
            if not i.__contains__('.json'):
                continue
            v = blockstate_file(str(folder_name).replace(blockstates_path, '')
                                .replace('\\', '/'), str(i).replace('.json', ''))
            result.append(v)
    return result


def scan_tags(path: str, namespace: str):
    result = []
    for folder_name, sub_folders, filenames in os.walk(path):
        if not folder_name.__contains__('tags'):
            continue
        for i in filenames:
            if not i.__contains__('.json'):
                continue
            v = tag_file(namespace, str(folder_name)
                         .replace('\\', '/')
                         .replace(path + 'tags/', ''), str(i).replace('.json', ''))
            result.append(v)
    return result


def scan_langs():
    result = []
    for folder_name, sub_folders, filenames in os.walk(archive_path + 'lang/'):
        for i in filenames:
            result.append(lang_file(i.replace('.json', '')))
    return result


def scan_loots():
    result = []
    for folder_name, sub_folders, filenames in os.walk(kuayue_data + 'loot_tables/'):
        for i in filenames:
            if not i.__contains__('.json'):
                continue
            v = loot_table_file(folder_name.replace(kuayue_data + 'loot_tables/', '').replace('\\', '/')
                                , i.replace('.json', ''))
            result.append(v)
    return result


def scan_advancements():
    result = []
    for folder_name, sub_folders, filenames in os.walk(kuayue_data + 'advancements/'):
        for i in filenames:
            if not i.__contains__('.json'):
                continue
            v = advancement_file(i.replace('.json', ''))
            result.append(v)
    return result


def scan_recipes():
    result = []
    for folder_name, sub_folders, filenames in os.walk(kuayue_data + 'recipes/'):
        for i in filenames:
            if not i.__contains__('.json'):
                continue
            v = recipe_file(folder_name.replace(kuayue_data + 'recipes/', ''), i.replace('.json', ''))
            result.append(v)
    return result


def load_all():
    global blockstates_list
    blockstates_list += scan_blockstates()
    global lang_list
    lang_list += scan_langs()
    global loot_tables_list
    loot_tables_list += scan_loots()
    global tags_list
    tags_list += scan_tags(minecraft_data, 'minecraft')
    tags_list += scan_tags(kuayue_data, 'kuayue')
    tags_list += scan_tags(forge_data, 'forge')
    tags_list += scan_tags(create_data, 'create')
    global advancements_list
    advancements_list += scan_advancements()
    global recipes_list
    recipes_list += scan_recipes()
    for m in blockstates_list:
        m.read()
    for m in lang_list:
        m.read()
    for m in tags_list:
        m.read()
    for m in loot_tables_list:
        m.read()
    for m in advancements_list:
        m.read()
    for m in recipes_list:
        m.read()
    print()
    print('Loaded', len(blockstates_list), 'block state files.')
    print('Loaded', len(tags_list), 'tag files.')
    print('Loaded', len(loot_tables_list), 'loot files.')
    print('Loaded', len(advancements_list), 'advancement files.')
    print('Loaded', len(recipes_list), 'recipe files.')


def mv_blockstate(old_path: str, new_path: str):
    path = ''
    path2 = ''
    if old_path.__contains__('/'):
        index = old_path.rfind('/')
        path = old_path[0:index:]
        old_key = old_path[index + 1::]
    else:
        old_key = old_path
    if new_path.__contains__('/'):
        index = new_path.rfind('/')
        path2 = new_path[0:index:]
        new_key = new_path[index + 1::]
    else:
        new_key = new_path
    should_act = False

    for i in blockstates_list:
        if i.path == path and i.name == old_key:
            i.rename_and_move(path2, new_key)
            should_act = True
            break

    if should_act:
        for i in lang_list:
            i.on_blockstate_rename(old_key, new_key)
        for i in tags_list:
            i.on_blockstate_rename(old_key, new_key)
        for i in advancements_list:
            i.on_blockstate_rename(old_key, new_key)
        for i in recipes_list:
            i.on_blockstate_rename(old_key, new_key)
        for i in loot_tables_list:
            i.on_blockstate_rename(old_key, new_key)
    print('Successfully moved ' + old_key + ' to ' + new_key)


def save_all():
    for i in blockstates_list:
        i.write()
    for i in tags_list:
        i.write()
    for i in advancements_list:
        i.write()
    for i in recipes_list:
        i.write()
    for i in loot_tables_list:
        i.write()


def search(mode: bool, *keys):
    result = []
    if len(keys) == 0:
        return result
    for i in blockstates_list:
        for j in keys:
            if i.name.__contains__(j) and i.name not in result:
                result.append(((i.path + '/') if i.path != '' else '').replace('\\', '/') + i.name)
    removal_list = []
    if mode:
        for i in result:
            for j in keys:
                if not i.__contains__(j):
                    removal_list.append(i)
                    continue
        for i in removal_list:
            result.remove(i)
    return result


def search_by_tokens(*tokens):
    if len(tokens) < 2:
        print('Abnormal parameter list length')
        return []
    mode = False
    for i in tokens:
        if i == '--and':
            mode = True
        elif i == '--or':
            mode = False
    param_list = [i for i in tokens[1::] if not i.startswith('--')]
    if len(param_list) < 1:
        print('Abnormal parameter list length')
        return []
    result = search(mode, *param_list)
    return result


def show_helps():
    print('''
    search: 
    search a certain key
    usage: search *keys (optional params)
    e.g.: search marshalled cr200j panel (--or/--and)
    optional params:
    --and return names contain all the keys
    --or return names contain any key given(default)
    :return: file name which contain the key
    
    mv:
    change a key's name
    usage: mv old_name new_name
    e.g.: mv door_original_25g door_25g
    
    bundled:
    batch processing the names:
    usage: bundled key
    e.g.:bundled cr200j
    :return1: all searched names
    if chosen y as bundled rename:
    rename all searched keys by user input one by one
    
    pull:
    pull the commits from the reposity
    requires git added to path

    push:
    push the current commits to the reposity
    requires git added to path

    commit:
    commit the current changes
    usage: commit <information>
    e.g.: commit test
    requires git added to path

    help:
    show all the usages of the commands
    
    exit:
    exit the program
    ''')


def get_cached_path(path: str):
    if path == '':
        return ''
    path = path.replace('\\', '')
    if path.endswith('/'):
        return path
    return path + '/'


def get_name_from_path(path: str):
    path = path.replace('\\', '/')
    if not path.__contains__('/'):
        return path
    return path[path.rfind('/') + 1::]


def process_command(command: str, cached_path: str):
    length = len(command)
    while True:
        command = command.replace('  ', ' ')
        if len(command) == length:
            break
        length = len(command)
    tokens = command.split(' ')
    if len(tokens) == 0:
        return 0
    if tokens[0] == '':
        return 0
    if tokens[0] == 'exit':
        save_all()
        return 1
    if tokens[0] == 'pull':
        os.system('git pull')
    if tokens[0] == 'push':
        os.system('git push')
    if tokens[0] == 'commit':
        os.system('git add .')
        os.system('git commit -m ' + tokens[1] + ' assets\')
    if tokens[0] == 'mv':
        if len(tokens) != 3:
            print('Abnormal parameter list length')
            return 0
        if tokens[2].__contains__(' ') or len(tokens[2]) < 1:
            print('Invalid new name!')
            return 0
        mv_blockstate(tokens[1], tokens[2])
    if tokens[0] == 'path':
        if len(tokens) < 2:
            print('Abnormal parameter list length')
            return 0
        cached_path = tokens[1]
    if tokens[0] == 'help':
        show_helps()
        return 0
    if tokens[0] == 'search':
        result = search_by_tokens(*tokens)
        for i in result:
            print('-->', i)
        print('Find', len(result), 'results')
    if tokens[0] == 'bundled':
        bundled = search_by_tokens(*tokens)
        if len(bundled) == 0:
            return 0
        for i in bundled:
            print('-->', i)
        print('Find', len(bundled), 'results')
        sub_key = input('start bundled rename? [y/n]')
        if not sub_key == 'y':
            return
        print('type \'/exit\' to quit bundle processing')
        print('type \'/skip\' to skip the recent object')
        skip = 0
        counter = 0
        for i in bundled:
            new_name = input('[' + str(counter + 1) + '/' + str(len(bundled)) + '] -> rename ' + i + ' as ')
            if new_name == '/exit':
                print('quit bundled mode.')
                break
            if new_name == '/skip':
                skip += 1
                counter += 1
                continue
            if not new_name.__contains__(' ') and len(new_name) > 0:
                mv_blockstate(i, get_cached_path(cached_path) + new_name.replace('~', get_name_from_path(i)))
                counter += 1
        print('Successfully renamed', counter, 'files, skip', skip)


def gen_init_prog(blockstate: blockstate_file):
    props = blockstate.get_properties()
    material = 'Material.METAL'
    color_base = 'MaterialColor.'
    fx = 0
    fy = 0
    lx = 1
    ly = 1
    block_type = 'TrainPanelBlock'
    if blockstate.name.__contains__('panel'):
        if blockstate.name.__contains__('wide'):
            fx = -1
            fy = 0
            lx = 2
            ly = 2
        if props.__contains__('hinge'):
            block_type = 'TrainHingePanelBlock'
        rst = init_prog(blockstate.name, block_type, material, color_base + 'COLOR_GREEN',
                        first_x=fx, first_y=fy, last_x=lx, last_y=ly)
        print(rst)


def init_prog(reg_key: str, block_type: str, material: str = 'Material:METAL',
              color: str = 'MaterialColor.COLOR_GREEN', tab: str = 'AllElements.neoKuayueMainTab',
              first_x: int = 0, first_y: int = 0,last_x: int = 1, last_y: int = 1):
    rst = 'public static final PanelRegistration<' + block_type + '> ' + reg_key.upper() + ' =\n    new PanelRegistration<' + block_type + '>(\"' + reg_key + '\")\n'
    rst += '    .block(p -> new ' + block_type + '(p, new Vec2(' + str(first_x) + ', ' + str(first_y) + '), new Vec2(' + str(last_x) + ', ' + str(last_y) + ')))\n'
    rst += '    .materialAndColor(' + material + ', ' + color + ')\n    .tab(' + tab + ')\n    .noOcclusion()\n    .submit(' \
                                                                                   'AllElements.testRegistry);'
    return rst


def rename_item_model():
    files = []
    for folder_name, sub_folder, file_name in os.walk(archive_path + 'models/item'):
        for x in file_name:
            # if x.__contains__('window') or x.__contains__('panel') or x.__contains__('end_face') or x.__contains__('slab') or x.__contains__('carport') or x.__contains__('front') or x.__contains__('head') or x.__contains__('air'):
            if x.__contains__('cr200j_skirt'):
                files.append(x)

    for k in files:
        contents = None
        with open(archive_path + 'models/item/' + k, 'r') as f:
            contents = f.read()
        command = input('rename ' + k.replace('.json', '') + ' as -> ')
        if command == '/skip':
            continue
        os.remove(archive_path + 'models/item/' + k)
        with open(archive_path + 'models/item/' + command + '.json', 'w') as f:
            f.write(contents)


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    langs = scan_langs()
    for i in langs:
        i.write()
    cached_path = ''
    '''
    result_blockstate = []
    valid_prop_list = ['facing', 'open', 'hinge']
    print()
    for i in blockstates_list:
        if (i.name.__contains__('panel') or i.name.__contains__('window')) and i.name.__contains__('cr200j'):
            for j in i.get_properties():
                if j not in valid_prop_list:
                    break
                result_blockstate.append(i)
                print(i.name)
    '''
    # rename_item_model()
    # test_bs = blockstate_file('panel/c200j', 'panel_middle_logo_cr_marshalled_cr200j')
    # test_bs.read()
    # gen_init_prog(test_bs)
    # while True:
        # command = input('[bs]')
        # key = process_command(command, cached_path)
        # if key == 1:
            # break